package com.jspxcms.plug.web.back;

import com.jspxcms.common.orm.LimitRequest;
import com.jspxcms.common.orm.Limitable;
import com.jspxcms.common.orm.RowSide;
import com.jspxcms.common.web.Servlets;
import com.jspxcms.core.support.Constants;
import com.jspxcms.core.support.Context;
import com.jspxcms.plug.domain.*;
import com.jspxcms.plug.service.PlugDiseaseService;
import com.jspxcms.plug.service.PlugDoctorDiseaseService;
import com.jspxcms.plug.service.PlugDoctorService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefaults;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.jspxcms.core.support.Constants.*;

@Controller
@RequestMapping("/plug/doctor")
public class DoctorController {
    private static final Logger logger = LoggerFactory
            .getLogger(DoctorController.class);

    @RequiresPermissions("plug:doctor:list")
    @RequestMapping("list.do")
    public String list(
            Integer did,
            @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable,
            HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model modelMap) {
        if (did == null) {
            try {
                response.getWriter().write("<script>alert('请先选择所属医院和科室');window.location.href='../hospital/list.do'</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        Integer siteId = Context.getCurrentSiteId(request);
        Map<String, String[]> params = Servlets.getParameterValuesMap(request,
                Constants.SEARCH_PREFIX);
        Page<PlugDoctor> pagedList = service.findAll(siteId, params, pageable);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("did", did);
        return "plug/doctor/doctor_list";
    }

    @RequiresPermissions("plug:doctor:create")
    @RequestMapping("create.do")
    public String create(Integer id, Integer did, org.springframework.ui.Model modelMap) {
        PlugDoctor bean = null;
        if (id != null) {
            bean = service.get(id);
            modelMap.addAttribute("bean", bean);
            if (did != null && bean != null && bean.getDepartment() != null) {
                did = bean.getDepartment().getId();
            }
        }
        initDiseases(modelMap, bean);
        modelMap.addAttribute(OPRT, CREATE);
        modelMap.addAttribute("did", did);
        return "plug/doctor/doctor_form";
    }

    @RequiresPermissions("plug:doctor:edit")
    @RequestMapping("edit.do")
    public String edit(
            Integer id,
            Integer did,
            Integer position,
            @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId(request);
        PlugDoctor bean = service.get(id);
        Map<String, String[]> params = Servlets.getParameterValuesMap(request,
                Constants.SEARCH_PREFIX);
        RowSide<PlugDoctor> side = service.findSide(siteId, params, bean, position,
                pageable.getSort());
        modelMap.addAttribute("bean", bean);
        if (did == null && bean != null && bean.getDepartment() != null) {
            did = bean.getDepartment().getId();
        }
        initDiseases(modelMap, bean);
        modelMap.addAttribute("did", did);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        modelMap.addAttribute(OPRT, EDIT);
        return "plug/doctor/doctor_form";
    }

    @RequiresPermissions("plug:doctor:save")
    @RequestMapping("save.do")
    public String save(@Valid PlugDoctor bean,
                       Integer did,
                       String[] diseases,
                       String smallImage,
                       String redirect,
                       HttpServletRequest request, RedirectAttributes ra) {
        if (did != null) {
            Integer siteId = Context.getCurrentSiteId(request);
            PlugHospitalDepartment department = new PlugHospitalDepartment();
            department.setId(did);
            bean.setDepartment(department);
            bean.setfLogo(smallImage);
            service.save(bean, diseases);
            logger.info("save PlugDoctor, name={}.", bean.getfDoctorName());
            ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
            ra.addAttribute("did", bean.getDepartment().getId());
            if (Constants.REDIRECT_LIST.equals(redirect)) {
                return "redirect:list.do";
            } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
                return "redirect:create.do";
            } else {
                ra.addAttribute("id", bean.getId());
                return "redirect:edit.do";
            }
        } else {
            return "redirect:list.do";
        }
    }

    @RequiresPermissions("plug:doctor:update")
    @RequestMapping("update.do")
    public String update(Integer did,
                         String[] diseases,
                         String smallImage,
                         @ModelAttribute("bean") PlugDoctor bean, Integer position,
                         String redirect, RedirectAttributes ra) {
        PlugHospitalDepartment department = new PlugHospitalDepartment();
        department.setId(did);
        bean.setDepartment(department);
        bean.setfLogo(smallImage);
        service.update(bean, diseases);
        logger.info("update PlugDoctor, name={}.", bean.getfDoctorName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }

    @RequiresPermissions("plug:doctor:delete")
    @RequestMapping("delete.do")
    public String delete(Integer[] ids, RedirectAttributes ra) {
        PlugDoctor[] beans = service.delete(ids);
        for (PlugDoctor bean : beans) {
            logger.info("delete PlugDoctor, name={}.", bean.getfDoctorName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }


    /**
     * 初始化
     *
     * @param modelMap
     * @param doctor
     */
    private void initDiseases(org.springframework.ui.Model modelMap, PlugDoctor doctor) {
        Limitable limitable = new LimitRequest(0, Integer.MAX_VALUE);
        List<PlugDisease> diseases = diseaseService.findList(null, limitable);
        List<PlugDiseaseExt> exts = new ArrayList<PlugDiseaseExt>();

        HashSet<Integer> checked = new HashSet<Integer>();
        if (doctor != null) {
            List<PlugDoctorDisease> temp = doctorDiseaseService.findByFDoctorId(doctor.getId());
            if (checked != null) {
                for (PlugDoctorDisease item : temp) {
                    checked.add(item.getfDiseaseId());
                }
            }
        }

        for (PlugDisease disease : diseases) {
            PlugDiseaseExt ext = new PlugDiseaseExt();
            ext.setChecked(checked.contains(disease.getId()));
            ext.setId(disease.getId());
            ext.setfDiseaseName(disease.getfDiseaseName());
            exts.add(ext);
        }
        modelMap.addAttribute("diseases", exts);
    }


    @ModelAttribute("bean")
    public PlugDoctor preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? service.get(oid) : null;
    }

    @Autowired
    private PlugDoctorDiseaseService doctorDiseaseService;

    @Autowired
    private PlugDiseaseService diseaseService;

    @Autowired
    private PlugDoctorService service;
}
